package com.spark.trouble

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.alert
import com.spark.common.ext.report
import com.spark.common.ext.success
import com.spark.common.ext.wrapIO
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import kotlinx.android.synthetic.main.frag_schema_brief.*

/**
 * [待办]-> 重大治理任务 -> 待审核 -> 方案简述vae
 */
class SchemaBriefFragment : BaseFragment() {
    private var taskId = ""

    companion object {
        fun newInstance(taskId: String): SchemaBriefFragment {
            val target = SchemaBriefFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_schema_brief
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@SchemaBriefFragment.taskId = this
                fetchInfo(taskId)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank()) {
                                alert("请输入驳回理由")
                            } else {
                                d.dismiss()
                                submitReject(this@SchemaBriefFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitResolve(taskId) }
    }

    @SuppressLint("SetTextI18n")
    private fun restore(
            respAll: String,
            limit: String,
            handleBrief: String
    ) {
        tv_resp_all.text = respAll
        tv_limit.text = "${limit}天"
        et_schema_brief.setText(handleBrief)
    }

    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agencty_major_fetch_verify}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, SchemeBriefModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        restore(
                                                approver_name,
                                                "$rectify_day",
                                                solution_content
                                        )
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    /**
     * [待办] 待审核 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitResolve(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_major_submit_verify}", mutableMapOf("taskId" to taskId, "approveState" to "2").toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )

    }

    @SuppressLint("CheckResult")
    private fun submitReject(taskId: String, reason: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", mutableMapOf("taskId" to taskId, "refuseReason" to reason).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }
}

data class MajorAgencyInfoModel(
        var msg: String = "",
        var code: String = "",
        var data: Any = Any(),
        var resultMaps: MutableList<ResultMaps> = mutableListOf()
) {
    data class ResultMaps(
            var source_processor_id: Int = 0,
            var trouble_level: String = "",
            var solution_type: Int = 0,
            var task_id: String = "",
            var process_time: Long = 0,
            var trouble_content: String = "",
            var responsible_user_id: Int = 0,
            var URL: String = "",
            var fatal: Boolean = false,
            var solution_content: String = "",
            var solution_plan: String = "",
            var solution_funding: String = "",
            var responsible_remark: String = "",
            var solutionPlan: MutableList<SolutionPlan> = mutableListOf(),
            var solutionContent: MutableList<SolutionContent> = mutableListOf(),
            var solutionFunding: MutableList<SolutionFunding> = mutableListOf(),
            var approve_remark: String = "",
            var responsible_money: String = "",
            var rectify_day: Int = 0,
            var processor_id: Int = 0,
            var responsible_leader_name: String = "",
            var acceptor_name: String = "",
            var process_type: String = "",
            var source_processor_name: String = "",
            var technician_name: String = "",
            var source_score: Int = 0,
            var approver_id: Int = 0,
            var approver_name: String = "",
            var source_money: String = "",
            var main_id: Int = 0,
            var source_category: String = "",
            var responsible_leader_id: Int = 0,
            var technician_id: Int = 0,
            var accpet_reason: String = "",
            var responsible_user_name: String = "",
            var acceptor_id: Int = 0,
            var responsible_score: Int = 0,
            var source_id: Int = 0,
            var responsible_department_id: Int = 0,
            var responsible_department_name: String = "",
            var source_description: String = ""
    )

    data class SolutionPlan(
            var filename: String = "",
            var uri: String = "",
            var fileId: String = ""
    )

    data class SolutionContent(
            var subtaskId: String = "",
            var docId: String = "",
            var docUsage: String = "",
            var number: String = "",
            var url: String = "",
            var fileId: String = "",
            var swfUrl: String = "",
            var filename: String = "")

    data class SolutionFunding(
            var filename: String = "",
            var uri: String = "",
            var fileId: String = ""
    )

    /**
     * 责任内容
     */
    data class RespContent(
            var score: String = "", // 0
            var money: String = "", // 0
            var remark: String = "", //  隐患升级
            var departmentId: String = "", // 25
            var departmentName: String = "", // 通风安全科
            var leaderId: String = "", // 21
            var leaderName: String = "", // 闫老师
            var userId: String = "", // 20
            var userName: String = "" // 袁建
    )
}

/**
 * 方案简述
 */
data class SchemeBriefModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var source_processor_id: Int = 0, // 19
            var trouble_level: String = "", // 重警
            var solution_type: Int = 0, // 0
            var solution_chief_id: Int = 0, // 21
            var fatal_reason: String = "", // 隐患升级
            var task_id: Int = 0, // 1873
            var fatal_approver_id: Int = 0, // 21
            var trouble_content: String = "", // 使用非抗静电、非阻燃风筒
            var fatal: Boolean = false, // false
            var processName: String = "", // 张峰
            var fatal_approver_remark: String = "",
            var rectify_day: Int = 0, // 0
            var processor_id: Int = 0, // 19
            var solution_goal: String = "", // 隐患升级
            var process_type: Int = 0, // 1
            var solution_time_limit: Long = 0, // 1531281600000
            var solution_content: String = "", // 隐患升级
            var source_processor_name: String = "", // 张峰
            var fatal_approver_name: String = "", // 闫老师
            var source_score: Int = 0, // 3
            var approver_id: Int = 0, // 21
            var approver_name: String = "", // 闫老师
            var source_money: Double = 0.0, // 200.00
            var main_id: Int = 0, // 1872
            var solution_plan: String = "", // 隐患升级
            var solution_funding: String = "", // 隐患升级
            var responsible_remark: String = "", // {'score':'0','money':'0','remark':' 隐患升级','departmentId':'25','departmentName':'通风安全科','leaderId':'21','leaderName':'闫老师','userId':'20','userName':'袁建'}
            var source_id: Int = 0, // 2
            var source_description: String = "" // 使用非抗静电、非阻燃风筒
    )
}